const http = require("http")
const fs = require('fs')
const ejs = require('ejs');

const {readFile} = require('./src/file/file-opt')
const {renderPage} = require('./src/file/renderPage')
const path = require("path")


const hostname = "127.0.0.1"
const port = "8888"

const options = {
    hostname: hostname,
    port: port,
    path: "/",
    methods: "GET",
    headers: {
        'Content-Type': 'application/json',
        // 'Content-Length': data.length
    }
}


const app = http.createServer()


app.on("request", (req, res) => {
    console.log("req.url", req.url)
    const url = req.url

    if (url === "/") {
        res.statusCode = 200
        res.setHeader("Content-Type", "text/plain;charset=utf-8;")
        res.end("首页")
    } else if (url.includes("login")) {
        res.statusCode = 200
        res.setHeader("Content-Type", "text/html;charset=utf-8;")

        readFile("public/json/data.json").then(resData => {
            const {code, message, data} = JSON.parse(resData)
            // res.append('Link', ['<link rel="stylesheet" href="public/css/style.css"/>']);
            // 渲染页面
            const pages = renderPage(data)
            res.write('<meta charset="UTF-8"/>')
            res.write('<title>node响应</title>')
            res.write('<link rel="stylesheet" href="/css/style.css"/>')
            res.write(pages, "utf8");

            res.end()
        }).catch(error => {
            console.log(error)
        })
    } else {
        res.statusCode = 404
    }
    res.on('data', d => {
        console.log("d:", d)
        process.stdout.write(d)
    })
})

app.listen(port, () => {
    console.log(`服务器运行在${hostname}:${port}`)
})
